<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        img{
            width: 100px;
            height: auto;
        }
    </style>
    <script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
</head>

<body>
<form id="uploadForm">
    <input type="file" class="fileType" name="file">
    <button type="button" class="button">提交</button>
    <img class="picture">
</form>
<script>
    $(".button").click(function (){
        //获取表单数据，包括文件
        let formData=new FormData($("#uploadForm")[0])
        $.ajax({
            type:"post",
            url:"/fileServlet",
            data:formData,
            contentType: false, // 防止 jQuery 自动设置内容类型
            processData: false, // 防止 jQuery 处理数据
            success:function(data){
                if (data==="true"){
                    alert("提交成功")
                }else{
                    alert("提交失败")
                }
            },
            error:function(){
                alert("文件上传错误")
            }
        })
    })
    document.querySelector(".fileType").addEventListener('change',function(even){
        let file=even.target.files[0]
        if (file){
            let reader=new FileReader()
            reader.onload = function(e){
                let picture=document.querySelector(".picture")
                picture.src=e.target.result
            }
            reader.readAsDataURL(file);  // 读取文件内容，转化为 Data URL (base64)
        }
    })

</script>
</body>

</html>